﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AutoFacUtils;
using FluentValidation;
using CashFlow.Web.Common;
using CashFlow.Web.Service;
using CashFlow.Web.Def;
using CashFlow.Web.Models.Order;

namespace CashFlow.Web.Validator.Order
{
    public class ReceiptPaymentModelValidator
        : AbstractValidator<ReceiptPaymentModel>
    {
        private static IOrderService GetOrderService() { return AutoFacHelper.Get<IOrderService>(); }
        private static IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }

        public ReceiptPaymentModelValidator()
        {
            CascadeMode = CascadeMode.Stop;
            RuleFor(x => x.OrderId).Must((x, y) => IsValidOrderId(x))
                .WithMessage("非法OrderId & BuyerUserId");
        }

        private bool IsValidOrderId(ReceiptPaymentModel model)
        {
            var date = MyCommonTool.GetOrderDate();
            var userService = GetUserService();
            var ui = userService.GetLoginUser();
            var orderService = GetOrderService();
            var n = orderService.Count(
                        x => x.Id == model.OrderId
                        && x.CreateTime.ToString("yyyy-MM-dd") == date
                        && x.BuyerUserId == model.BuyerUserId
                        && x.SellerUserId == ui.Id
                        && (x.State == (int)EOrderState.NotPaied
                            || x.State == (int)EOrderState.Paied
                        )
                    );
            return n > 0;
        }
    }
}